package shop.controller.front.user;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.FrontBaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.plugins.sms.SMS;
import shop.core.plugins.sms.SMSSendCodeResult;
import shop.core.plugins.sms.SMSVerifyCodeResult;
import shop.core.util.MD5;
import shop.core.util.QRcodeUtils;
import shop.services.front.product.ProductService;
import shop.services.front.product.bean.Product;
import shop.services.front.rank.RankService;
import shop.services.front.rank.bean.Rank;
import shop.services.front.systemSetting.SystemSettingService;
import shop.services.front.systemSetting.bean.SystemSetting;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by wzl on 2017/9/21.
 *
 * @描述：用户
 */
@Controller
@RequestMapping("/front/user/")
public class UserController extends FrontBaseController<User> {
    @Resource
    private UserService userService;
    @Resource
    private RankService rankService;
    @Resource
    private ProductService productService;
    @Resource
    private SystemSettingService systemSettingService;

    @Override
    public Services<User> getService() {
        return userService;
    }


    /**
     * 跳转到我的首页
     *
     * @return
     */
    @RequestMapping("toMyPage")
    public String toMyPage() {
        return "/front/user/userList";
    }

    /**
     * 跳转到我的收藏页面
     *
     * @return
     */
    @RequestMapping("toMyFavorite")
    public String toMyFavorite() {
        return "/front/user/collectionList";
    }


    /**
     * 跳转到我的足迹页面
     *
     * @return
     */
    @RequestMapping("toMyFoot")
    public String toMyFoot() {
        return "/front/user/browseRecord";
    }

    /**
     * 跳转到分销商的信息设置页面
     *
     * @return
     */
    @RequestMapping("toSellerSet")
    public String toSellerSet() {
        return "/front/user/informationSetting";
    }

    /**
     * 跳转到个人中心页面
     *
     * @return
     */
    @RequestMapping("toUserInfo")
    public String toUserInfo() {
        return "/front/user/userCenter";
    }

    /**
     * 跳转到店铺设置
     *
     * @return
     */
    @RequestMapping("toStoreSet")
    public String toStoreSet() {
        return "/front/seller/storeSet";
    }

    /**
     * 跳转到查看店铺
     *
     * @return
     */
    @RequestMapping("toMyStore")
    public String toMyStore() {
        return "/front/seller/myStore";
    }

    /**
     * 跳转到查看店铺（分销商）
     *
     * @return
     */
    @RequestMapping("toSellerMyStore")
    public String toSellerMyStore() {
        return "/front/seller/sellerMyStore";
    }

    /**
     * 跳转到我的团队
     *
     * @return
     */
    @RequestMapping("toMyTeam")
    public String toMyTeam() {
        return "/front/seller/myTeam";
    }

    /**
     * 跳转到分销商订单
     *
     * @return
     */
    @RequestMapping("toSellerOrder")
    public String toSellerOrder() {
        return "/front/seller/sellerOrder";
    }

    /**
     * 跳转到成员信息
     *
     * @return
     */
    @RequestMapping("toMySubDetail")
    public String toMySubDetail() {
        return "/front/seller/personInf";
    }

    /**
     * 跳转到我的分销
     *
     * @return
     */
    @RequestMapping("toMySub")
    public String toMySub() {
        return "/front/user/distributor";
    }

    /**
     * 跳转到绑定手机页面
     *
     * @return
     */
    @RequestMapping("toBind")
    public String toBind() {
        return "/front/user/bindPhone";
    }

    /**
     * 跳转到会员等级页面
     *
     * @return
     */
    @RequestMapping("toRankList")
    public String toRankList() {
        return "/front/seller/rankList";
    }

    /**
     * 跳转到分销商提示页面
     *
     * @return
     */
    @RequestMapping("toSellerNotice")
    public String toSellerNotice() {
        return "/front/seller/notice";
    }

    /**
     * 跳转到我的名片页面
     *
     * @return
     */
    @RequestMapping("toMyCard")
    public String toMyCart() {
        return "/front/seller/myCard";
    }

    /**
     * 跳转到分享商品页面
     *
     * @return
     */
    @RequestMapping("toShare")
    public String toShare() {
        return "/front/seller/share";
    }


    /**
     * 跳转到二维码扫描
     *
     * @return
     */
    @RequestMapping("toUserCode")
    public String toUserCode() {
        return "/front/account/qrCode";
    }

    /**
     * 查询登录用户
     *
     * @param
     * @return
     */
    @RequestMapping(value = "selectUser", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectUser(HttpSession session) {
        User user = (User) session.getAttribute("userInfo");
        if (!StringUtils.isBlank(user.getRankID())) {
            Rank rank = new Rank();
            rank.setId(user.getRankID());
            rank = rankService.selectOne(rank);
            user.setRankName(rank.getType());
        } else {
            user.setRankName("普通会员");
        }
        jsonResult = new JSONResult();
        jsonResult.setData(user);
        return jsonResult;
    }


    /**
     * 查询系统设置
     *
     * @param
     * @return
     */
    @RequestMapping(value = "selectSystemSetting", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectSystemSetting() {
        SystemSetting setting = systemSettingService.selectOne(new SystemSetting());
        jsonResult = new JSONResult();
        jsonResult.setData(setting);
        return jsonResult;
    }

    /**
     * 查询登录用户(用于分销商分享名片)
     *
     * @param
     * @return
     */
    @RequestMapping(value = "selectUserDetail", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectUserDetail(User user) {
        user = userService.selectOne(user);
        jsonResult = new JSONResult();
        jsonResult.setData(user);
        return jsonResult;
    }

    /**
     * 查询店铺信息
     *
     * @param
     * @return
     */
    @RequestMapping(value = "selectStore", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectStore(HttpSession session) {
        jsonResult = new JSONResult();
        Product product = new Product();
        List<Product> rsList = productService.selectList(product);
        User user = new User();
        user.setRid("1");
        user = userService.selectOne(user);
        user.setProductAmount(rsList.size());
        jsonResult.setData(user);
        return jsonResult;
//        User user = (User) session.getAttribute("userInfo");
//        if("3".equals(user.getRid())){
//            if(!StringUtils.isBlank(user.getPid())){
//                User rs=new User();
//                rs.setId(user.getPid());
//                rs=userService.selectOne(rs);
//                rs.setProductAmount(rsList.size());
//                jsonResult.setData(rs);
//                return jsonResult;
//            }else{
//                User rs=new User();
//                rs.setRid("1");
//                rs=userService.selectOne(rs);
//                rs.setProductAmount(rsList.size());
//                jsonResult.setData(rs);
//                return jsonResult;
//            }
//        }else{
//            user.setProductAmount(rsList.size());
//            jsonResult.setData(user);
//            return jsonResult;
//        }
    }

    /**
     * 查询用户下级
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectSubList")
    @ResponseBody
    public JSONResult selectSubList(HttpSession session, User user) throws Exception {
        User rs = (User) session.getAttribute("userInfo");
        user.setPid(rs.getId());
        List<User> rsList = userService.selectList(user);
        for(User userInfo: rsList){
            Rank rank =new Rank();
            rank.setId(userInfo.getRankID());
            rank=rankService.selectOne(rank);
            userInfo.setRankName(rank.getType());
        }
        jsonResult = new JSONResult();
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 更新用户信息
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "updateUser", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateUser(HttpSession session, User user) throws Exception {
        User rs = (User) session.getAttribute("userInfo");
        user.setId(rs.getId());
        jsonResult = new JSONResult();
        userService.update(user);
        User rs2 = userService.selectOne(user);
        session.setAttribute("userInfo", rs2);//更新缓存
        return jsonResult;
    }

    /**
     * 发送验证码（绑定手机）
     *
     * @throws Exception
     */
    @RequestMapping(value = "getSMSCode", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult getSMSCode(HttpServletRequest request) throws Exception {
        JSONResult rs = new JSONResult();
        String mobile = request.getParameter("mobile");
        //根据手机号码查询用户信息，判断是否存在手机号码
        User user = new User();
        user.setPhone(mobile);
        List<User> userList = userService.selectList(user);

        if (userList.size() > 0) {
            rs.setSuccess(false);
            rs.setMessage("该手机已绑定其它账号，请重新填写手机号码！");
            return rs;
        }
        //发送短信
        SMS sms = new SMS();
        SMSSendCodeResult smsSendCodeResult = sms.sendCode(mobile, "5kDaOD-SQ8AbS959Lb9QRE", "86", null, null);
        if (smsSendCodeResult.getCode() == 200) {
            rs.setSuccess(true);
            rs.setMessage("短信发送成功！");
            rs.setData(smsSendCodeResult);
            logger.debug("验证码返回信息" + rs);
            return rs;
        } else {
            rs.setSuccess(false);
            rs.setMessage("短信发送失败！");
            return rs;
        }
    }

    /**
     * 校验验证码
     *
     * @throws Exception
     */
    @RequestMapping(value = "checkCode", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult checkCode(HttpServletRequest request) throws Exception {
        JSONResult jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute("userInfo");
        // SmsId 短信验证码唯一标识   SmsContent 短信验证码内容
        String smsId = request.getParameter("SmsId");
        String smsContent = request.getParameter("SmsContent");
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");
        SMS sms = new SMS();
        SMSVerifyCodeResult rs = sms.verifyCode(smsId, smsContent);//验证码验证方法
        if (rs.getSuccess() == null || !rs.getSuccess()) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("短信验证码错误！");
        } else {
            jsonResult.setSuccess(true);
            user.setPhone(phone);
            user.setUsername(phone);
            user.setPassword(MD5.md5(password));
            userService.update(user);
        }
        return jsonResult;
    }

//    /**
//     * 分享商品链接(由于目前商品只有一件，暂时弃用)
//     *
//     * @return jsonResult
//     * @throws Exception
//     */
//    @RequestMapping(value = "shareProduct", method = RequestMethod.GET)
//    @ResponseBody
//    public JSONResult shareProduct(HttpServletRequest request) throws Exception {
//        User user = (User) request.getSession().getAttribute("userInfo");
//        String mid=request.getParameter("mid");
//        QRcodeUtils qrCodeUtils = new QRcodeUtils();
//        String contents="http://www.pinrenzheng.cn/rest/front/product/toProductDetail?pid=" +user.getId()+"&mid="+mid;
//        logger.debug("我要分销二维码内容："+contents);
//        String qrCode = qrCodeUtils.createQrcode(request, contents);
//        JSONResult jsonResult = new JSONResult();
//        jsonResult.setData(qrCode);
//        return jsonResult;
//    }


}